import type { NextApiResponse } from 'next';
import multer from 'multer';
import { NextApiRequestWithFiles } from '@common/type/upload';
import path from 'path';
import R from '@common/type/response';
import { getUploadDir, generateUniqueFilename, getFileUrl } from '@common/utils/file';
import { AuthenticatedRequest, withAuth } from '@common/middleware/auth';

// 配置multer
const upload = multer({
    storage: multer.diskStorage({
        destination: (req, file, cb) => {
            // 使用工具函数获取上传目录
            const uploadDir = getUploadDir();
            cb(null, uploadDir);
        },
        filename: (req, file, cb) => {
            // 使用工具函数生成唯一文件名
            const filename = generateUniqueFilename(file.originalname);
            cb(null, filename);
        }
    }),
    limits: {
        fileSize: 5 * 1024 * 1024, // 限制5MB
    },
    fileFilter: (req, file, cb) => {
        // 只允许图片文件
        const allowedTypes = /jpeg|jpg|png|gif|webp/;
        const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
        const mimetype = allowedTypes.test(file.mimetype);

        if (mimetype && extname) {
            return cb(null, true);
        } else {
            cb(new Error('只允许上传图片文件!'));
        }
    }
});

// 处理multer中间件
const uploadMiddleware = upload.single('image');

// 包装multer中间件以支持Next.js API
const runMiddleware = (req: AuthenticatedRequest, res: NextApiResponse, fn: any) => {
    return new Promise((resolve, reject) => {
        fn(req, res, (result: any) => {
            if (result instanceof Error) {
                return reject(result);
            }
            return resolve(result);
        });
    });
};

export async function handler(req: NextApiRequestWithFiles, res: NextApiResponse) {
    if (req.method !== 'POST') {
        return R.error(res, '只支持POST请求');
    }

    try {
        // 运行multer中间件
        await runMiddleware(req, res, uploadMiddleware);

        if (!req.file) {
            return R.error(res, '没有上传文件');
        }

        // 使用工具函数获取文件URL
        const fileUrl = getFileUrl(req.file.filename);
        const data = {
            filename: req.file.filename,
            originalname: req.file.originalname,
            url: fileUrl,
            size: req.file.size,
            mimetype: req.file.mimetype
        }
        R.success(res, data);
    } catch (error: any) {
        console.error('文件上传错误:', error);
        R.error(res, error.message || '文件上传失败');
    }
}

// 配置API路由以处理文件上传
export const config = {
    api: {
        bodyParser: false, // 禁用默认的body解析器
    },
};

export default withAuth(handler); 